var job_kindData = require("job_kindData/job_kindData.js").job_kindData;
var internshipsData = require("../../dataTest/internshipData.js").internshipsData;
var citySelectData = require("job_kindData/job_kindData.js").citySelectData
var companyUtil = require('companyUtil/companyUtil.js');
var baseURL = getApp().globalData.baseURL;
var baseURLtest = getApp().globalData.baseURLtest;
var util = require("../../utils/util.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {

    swiper_company: true,
    swiper_internship: false,
    currentViewItem: 0,

    //部分遮罩层数据
    clientHeight: "", //屏幕可用高度
    overflow: "",
    nowrap: false,
    windowHeight: 0,
    intern_nowrap: false,

    //筛选框数据
    job_kindData: "", //行业对象列表
    jobKindlView: false, //行业筛选框显示
    kind_alive: false, //行业筛选框激活的样式
    citySelectData: citySelectData, //主要城市选择
    internship_trade_view: false,
    internship_trade_alive: false,
    city_view: false,
    city_alive: false,

    keyWord: null,
    trade: null, //当前选中的行业
    companies: [], //当前页面公司列表

    internTrade: null,
    internFlag: "all",
    internKeyword: "",
    internshipPositionData: [],
    internship_loading: true,
    internship_haveMore: true,
    internPageNow: 0,
    internMaxPage: false,

    dataFlag: "", //当前页面数据的标志（通过什么筛选而来）
    pageNow: 0, //当前页
    pageSize: 15, //每页数据条数
    maxPage: false, //当前页是否到达最大页
    loading: true, //“正在加载中”字样的显示
    haveMore: true, //“没有更多了”字样的显示

    isLogin: false, //是否有登录
    haveInfo: false, //是否有信息
    companyIdsOfCollection: [], //用户收藏的企业的id
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    //实习职位数据列表
    companyUtil.listInternshipPosition("", _this.data.internFlag, 0, this.data.pageSize).then((res) => {
      _this.setData({
        internshipPositionData: res,
        internship_loading: false,
        internship_haveMore: false,
      })
    })
    //设备信息
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          windowHeight: res.windowHeight,
        })
      },
    })
    var companyIdsOfCollection = [];
    //获取并设置用户详细信息,获取第一页数据
    wx.showLoading({
      title: '',
    })
    _this.getAndSetloginInfo().then(() => {
      //获取用户收藏
      if (_this.data.haveInfo) {
        var userProfileId = getApp().globalData.userProfile.id;
        companyUtil.findCompanyIdsOfCollection(userProfileId).then((res) => {
          companyIdsOfCollection = res;
          _this.setData({
            companyIdsOfCollection: companyIdsOfCollection
          })
          getApp().globalData.companyIdsOfCollection = companyIdsOfCollection;
        })
      }
      var search = options.search;
      if (search == "search") {
        var gotCompanies = [];
        var keyWord = options.keyWord;
        var pageNow = _this.data.pageNow;
        var pageSize = _this.data.pageSize;
        companyUtil.getCompanies(keyWord, "byKeyWord", pageNow, pageSize).then((res) => {
          gotCompanies = res;
          gotCompanies = companyUtil.addCollectedStatus(gotCompanies, companyIdsOfCollection);
          _this.setData({
            companies: gotCompanies,
            pageNow: 0,
            pageSize: 15,
            maxPage: false,
            loading: false,
            haveMore: false,
            dataFlag: "byKeyWord",
            keyWord: keyWord,
          })
        })
        wx.hideLoading();
      } else {
        //请求热门
        var hotCompanies = [];
        companyUtil.getHotCompanies().then((res) => {
          var hotCompanies = res;
          //请求普通数据
          var gotCompanies = [];
          var pageNow = _this.data.pageNow;
          var pageSize = _this.data.pageSize;
          companyUtil.getCompanies("", "all", pageNow, pageSize).then((res) => {
            gotCompanies = res;
            gotCompanies = hotCompanies.concat(gotCompanies);
            gotCompanies = companyUtil.addCollectedStatus(gotCompanies, companyIdsOfCollection);
            _this.setData({
              companies: gotCompanies,
              pageNow: 0,
              pageSize: 15,
              maxPage: false,
              loading: false,
              haveMore: false,
              dataFlag: "all",
            })
          })
        })
        wx.hideLoading();
      }
    });
    //设置其他数据
    _this.setData({
      job_kindData: job_kindData,
    })
    wx.getSystemInfo({
      success: function(res) {
        _this.setData({
          clientHeight: res.windowHeight,
          overflow: 'hidden',
          nowrap: false
        })
      }
    })
    wx.setNavigationBarTitle({
      title: '名企校招',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var _this = this;
    wx.showLoading({
      title: '',
    })
    _this.getAndSetloginInfo().then(() => {
      //获取用户收藏
      if (_this.data.haveInfo) {
        var userProfileId = getApp().globalData.userProfile.id;
        companyUtil.findCompanyIdsOfCollection(userProfileId).then((res) => {
          _this.setData({
            companyIdsOfCollection: res
          })
          getApp().globalData.companyIdsOfCollection = res;
          var gotCompanies = companyUtil.addCollectedStatus(_this.data.companies, res);
          _this.setData({
            companies: gotCompanies
          })

        })
      }
      wx.hideLoading();
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var _this = this;
    _this.setData({
      companies: [],
      loading: true,
      haveMore: true,

      internshipPositionData: [],
      internship_loading: true,
      internship_haveMore: true,
    })

    //实习职位数据列表
    companyUtil.listInternshipPosition(_this.data.internKeyword, _this.data.internFlag, 0, _this.data.pageSize).then((res) => {
      _this.setData({
        internshipPositionData: res,
        internship_loading: false,
        internship_haveMore: false,
      })
      wx.stopPullDownRefresh();
    })

    //获取标志，请求参数和页面数据
    var keyWord = this.data.keyWord;
    var flag = this.data.dataFlag;
    var pageNow = 0;
    var pageSize = this.data.pageSize;
    companyUtil.getCompanies(keyWord, flag, pageNow, pageSize).then((res) => {
      var gotCompanies = res;
      //增加收藏状态
      var companyIdsOfCollection = _this.data.companyIdsOfCollection;
      gotCompanies = companyUtil.addCollectedStatus(gotCompanies, companyIdsOfCollection);
      _this.setData({
        companies: _this.data.companies.concat(gotCompanies),
        pageNow: 0,
        pageSize: 15,
        maxPage: false,
        loading: false,
        dataFlag: flag,
      })
      wx.stopPullDownRefresh();
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    
  },

  /**
   * 公司列表下拉触底
   */
  company_onReachBottom: function(e) {
    var _this = this;
    if (!_this.data.maxPage) {
      this.setData({
        pageNow: (this.data.pageNow + 1),
        loading: true,
        haveMore: true
      })
      //获取标志，请求参数和页面数据
      var keyWord = this.data.keyWord;
      var flag = this.data.dataFlag;
      var pageNow = this.data.pageNow;
      var pageSize = this.data.pageSize;
      companyUtil.getCompanies(keyWord, flag, pageNow, pageSize).then((res) => {
        if (res == "" || res == null || res.length == 0) {
          _this.setData({
            maxPage: true,
            loading: false,
            haveMore: false
          })
        } else {
          var gotCompanies = res;
          //增加收藏状态
          var companyIdsOfCollection = _this.data.companyIdsOfCollection;
          gotCompanies = companyUtil.addCollectedStatus(gotCompanies, companyIdsOfCollection);
          _this.setData({
            companies: _this.data.companies.concat(gotCompanies),
            loading: false,
            dataFlag: flag,
            maxPage: false,
          })
        }
      })
    } else {
      this.setData({
        loading: false,
        haveMore: false
      })
    }
  },

  /**
   * 实习列表下拉触底
   */
  intern_onReachBottom: function(e) {
    var _this = this;
    if (!_this.data.internMaxPage) {
      this.setData({
        internPageNow: (this.data.internPageNow + 1),
        internship_loading: true,
        internship_haveMore: true,
      })
      //获取标志，请求参数和页面数据
      var internKeyword = this.data.internKeyword;
      var internFlag = this.data.internFlag;
      var internPageNow = this.data.internPageNow;
      var pageSize = this.data.pageSize;
      companyUtil.listInternshipPosition(internKeyword, internFlag, internPageNow, pageSize).then((res) => {
        if (res == "" || res == null || res.length == 0) {
          _this.setData({
            internMaxPage: true,
            internship_loading: false,
            internship_haveMore: false
          })
        } else {
          var gotInterns = res;
          //增加收藏状态
          _this.setData({
            internshipPositionData: _this.data.internshipPositionData.concat(gotInterns),
            internship_loading: false,
            internFlag: internFlag,
            internMaxPage: false,
          })
        }
      })
    } else {
      this.setData({
        internship_loading: false,
        internship_haveMore: false
      })
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var pages = getCurrentPages();
    var page = pages[pages.length - 1];
    var url = page.route;
    return {
      title: "香樟明人-校招网申",
      path: url
    }
  },

  //搜索框获得焦点
  wxSerchFocus: function(e) {
    wx.navigateTo({
      url: '/pages/company/search_page_company/search_page_com',
    })
  },

  //获取并设置用户登录状态与信息
  getAndSetloginInfo: function(e) {
    var _this = this;
    return new Promise(function(resolve, reject) {
      wx.showNavigationBarLoading();
      wx.getStorage({
        key: 'userLogin',
        success: function(res) {
          //设置登录状态
          _this.setData({
            isLogin: true
          })
          //设置全局用户数据
          getApp().globalData.userLogin = res.data;
          //请求详细信息,设置信息状态
          var userLoginId = getApp().globalData.userLogin.id;
          companyUtil.getUserProfile(userLoginId).then((res) => {
            _this.setData({
              haveInfo: res ? true : false
            })
            getApp().globalData.userProfile = res;
            wx.hideNavigationBarLoading();
            resolve();
          })
        },
        fail: function(res) {
          _this.setData({
            isLogin: false
          })
          wx.hideNavigationBarLoading();
          resolve();
        },
      })
    })
  },

  /**
   * 进入企业宣讲会与招聘列表
   */
  goCompanyWork: function(event) {
    wx.navigateTo({
      url: '/pages/company/company_work/company_work?companyId=' + event.currentTarget.dataset.companyId
    })
  },

  //校招名企点击行业分类
  jobKindSelect: function(e) {
    this.setData({
      jobKindlView: !this.data.jobKindlView,
      nowrap: !this.data.jobKindlView,
      kind_alive: !this.data.jobKindlView
    })
  },

  //校招名企点击行业的某一项
  select: function(e) {
    var _this = this
    var gotCompanies = [];
    var trade = e.currentTarget.dataset.trade;
    this.setData({
      jobKindlView: !this.data.jobKindlView,
      nowrap: !this.data.jobKindlView,
      kind_alive: !this.data.jobKindlView,
      companies: [],
      loading: true,
      haveMore: true,
      trade: trade,
      pageNow: 0,
      maxPage: false,
    })
    if (trade == "全部行业") {
      this.setData({
        keyWord: "",
        dataFlag: "all",
      })
      companyUtil.getHotCompanies().then((res) => {
        var hotCompanies = res;
        //请求普通数据
        var pageNow = _this.data.pageNow;
        var pageSize = _this.data.pageSize;
        companyUtil.getCompanies("", "all", pageNow, pageSize).then((res) => {
          gotCompanies = res;
          gotCompanies = hotCompanies.concat(gotCompanies);
          //增加收藏状态
          var companyIdsOfCollection = _this.data.companyIdsOfCollection;
          gotCompanies = companyUtil.addCollectedStatus(gotCompanies, companyIdsOfCollection);
          _this.setData({
            companies: gotCompanies,
            loading: false,
            haveMore: false,
          })
        })
      })
    } else {
      var pageNow = _this.data.pageNow;
      var pageSize = _this.data.pageSize;
      var tradeArr = trade.split("/");
      companyUtil.getCompanies(tradeArr, "byTrade", pageNow, pageSize).then((res) => {
        gotCompanies = res;
        //增加收藏状态
        var companyIdsOfCollection = _this.data.companyIdsOfCollection;
        gotCompanies = companyUtil.addCollectedStatus(gotCompanies, companyIdsOfCollection);
        _this.setData({
          keyWord: tradeArr,
          companies: gotCompanies,
          loading: false,
          haveMore: false,
        })
      })
    }
  },

  //校招名企点击收藏图标
  collecOnOne: function(e) {
    var event = e;
    var _this = this;
    if (!_this.data.isLogin) { //未登录
      wx.showModal({
        title: '提示',
        content: '你还没登录哦',
        success: function(res) {
          if (res.confirm) {
            //用户点击确认
            wx.switchTab({
              url: '/pages/my/my',
            })
          } else if (res.cancel) {
            //用户点击取消
          }
        }
      })
    } else if (_this.data.isLogin) { //已登录
      var haveInfo = _this.data.haveInfo;
      if (!this.data.haveInfo) {
        wx.showModal({
          title: '提示',
          content: '你还没填写个人简介哦',
          success: function(res) {
            if (res.confirm) {
              //用户点击确认
              wx.switchTab({
                url: '/pages/my/user_detail/detail',
              })
            } else if (res.cancel) {
              //用户点击取消
            }
          }
        })
      } else if (this.data.haveInfo) {
        //判断收藏状态
        //得到用户uid和宣讲会caid
        wx.showNavigationBarLoading();
        var isCollected = event.currentTarget.dataset.isCollected;
        var userProfileId = getApp().globalData.userProfile.id;
        var companyId = event.currentTarget.dataset.companyId;
        if (isCollected) {
          //已收藏，接下来取消
          wx.request({
            method: "DELETE",
            url: baseURLtest + "company_collection?companyId=" + companyId + "&userProfileId=" + userProfileId,
            header: getApp().globalData.header,
            data: {},
            success: function(res) {
              if (res.statusCode == 200) {
                wx.showToast({
                  title: '取消成功',
                })
                //重新更新页面的收藏
                var companyIdsOfCollection = getApp().globalData.companyIdsOfCollection;
                var companies = _this.data.companies;
                for (var i = 0; i < companyIdsOfCollection.length; i++) {
                  if (companyIdsOfCollection[i] == companyId) {
                    companyIdsOfCollection.splice(i, 1);
                    break;
                  }
                }
                companies = companyUtil.addCollectedStatus(companies, companyIdsOfCollection);
                getApp().globalData.companyIdsOfCollection = companyIdsOfCollection;
                _this.setData({
                  companies: companies,
                  companyIdsOfCollection: companyIdsOfCollection
                })
              } else {
                console.log(res);
                util.go404Page(res.statusCode, res.data);
              }
            },
            fail: function(res) {
              console.log(res);
              util.go404Page(res.statusCode, res.data);
            },
            complete: function(res) {
              wx.hideNavigationBarLoading();
            }
          })
        } else {
          //未收藏，接下来收藏
          var param = {
            userProfileId: userProfileId,
            companyId: companyId
          };
          param = JSON.stringify(param);
          wx.request({
            method: "POST",
            url: baseURLtest + "company_collection",
            header: getApp().globalData.header,
            data: param,
            success: function(res) {
              if (res.statusCode == 200) {
                wx.showToast({
                  title: '收藏成功',
                })
                //重新更新页面的收藏
                var companyIdsOfCollection = getApp().globalData.companyIdsOfCollection;
                var companies = _this.data.companies;
                companyIdsOfCollection.push(companyId);
                companies = companyUtil.addCollectedStatus(companies, companyIdsOfCollection);
                getApp().globalData.companyIdsOfCollection = companyIdsOfCollection;
                _this.setData({
                  companies: companies,
                  companyIdsOfCollection: companyIdsOfCollection
                })
              } else {
                console.log(res);
                util.go404Page(res.statusCode, res.data);
              }
            },
            fail: function(res) {
              console.log(res);
              util.go404Page(res.statusCode, res.data);
            },
            complete: function(res) {
              wx.hideNavigationBarLoading();
            }
          })
        }
      }
    }
  },

  //校招名企点击我的收藏
  collect: function() {
    var _this = this;
    if (!_this.data.isLogin) { //未登录
      wx.showModal({
        title: '提示',
        content: '你还没登录哦',
        success: function(res) {
          if (res.confirm) {
            //用户点击确认
            wx.switchTab({
              url: '/pages/my/my',
            })
          } else if (res.cancel) {
            //用户点击取消
          }
        }
      })
    } else if (_this.data.isLogin) { //已登录
      var haveInfo = _this.data.haveInfo;
      if (!_this.data.haveInfo) {
        wx.showModal({
          title: '提示',
          content: '你还没填写个人简介哦',
          success: function(res) {
            if (res.confirm) {
              //用户点击确认
              wx.switchTab({
                url: '/pages/my/user_detail/detail',
              })
            } else if (res.cancel) {
              //用户点击取消
            }
          }
        })
      } else if (_this.data.haveInfo) {
        wx.navigateTo({
          url: '/pages/company/com_collection/com_collection?userProfileId=' + getApp().globalData.userProfile.id,
        })
      }
    }
  },

  //校招名企上拉加载

  //点击校招名企
  showCompanyView: function(e) {
    var currentItem = e.currentTarget.dataset.currentItem;
    this.setData({
      swiper_company: true,
      swiper_internship: false,
      currentViewItem: currentItem,
    })
  },


  //点击实习职位
  showInternshipView: function(e) {
    var currentItem = e.currentTarget.dataset.currentItem;
    this.setData({
      swiper_company: false,
      swiper_internship: true,
      currentViewItem: currentItem,
    })
  },

  //左右滑动板块
  changCompanyView: function(e) {
    var currentItem = e.detail.current;
    if (currentItem == 0) {
      this.setData({
        swiper_company: true,
        swiper_internship: false,
      })
    } else if (currentItem == 1) {
      this.setData({
        swiper_company: false,
        swiper_internship: true,
      })
    }
  },

  //实习职位点击行业分类
  internshipSelect: function(e) {
    this.setData({
      internship_trade_view: !this.data.internship_trade_view,
      internship_trade_alive: !this.data.internship_trade_view,
      city_view: false,
      city_alive: false,
      intern_nowrap: !this.data.internship_trade_view,
    })
  },

  //实习职位点击城市选择
  citySelect: function(e) {
    this.setData({
      internship_trade_view: false,
      internship_trade_alive: false,
      city_view: !this.data.city_view,
      city_alive: !this.data.city_view,
      intern_nowrap: !this.data.city_view,
    })
  },

  //实习职位行业分类点击某一项
  internshipTradeSelectOne: function(e) {
    var _this = this;
    var trade = e.currentTarget.dataset.trade;
    this.setData({
      internship_trade_view: false,
      internship_trade_alive: false,
      intern_nowrap: false,
      internship_loading: true,
      internship_haveMore: true,
      internshipPositionData: [],
      internTrade: trade,
      internPageNow: 0,
      internMaxPage: false,
    })
    //请求数据，设置数据（页面标志，当前页面，页面数据大小，页面数据）
    if (trade == "全部行业") {
      this.setData({
        internFlag: "all",
        internKeyword: "",
      })
      //实习职位数据列表
      companyUtil.listInternshipPosition("", _this.data.internFlag, 0, this.data.pageSize).then((res) => {
        _this.setData({
          internshipPositionData: res
        })
      })
    } else {
      var internPageNow = _this.data.internPageNow;
      var pageSize = _this.data.pageSize;
      var tradeArr = trade.split("/");
      companyUtil.listInternshipPosition(tradeArr, "byTrade", internPageNow, pageSize).then((res) => {
        _this.setData({
          internFlag: "byTrade",
          internKeyword: tradeArr,
          internshipPositionData: res,
          internship_loading: false,
          internship_haveMore: false,
        })
      })
    }
  },

  //实习职位城市分类点击某一项
  internshipCitySelectOne: function(e) {
    var _this = this;
    var city = e.currentTarget.dataset.city;
    this.setData({
      city_view: false,
      city_alive: false,
      intern_nowrap: false,
      internship_loading: true,
      internship_haveMore: true,
      internshipPositionData: [],
      internTrade: city,
      internPageNow: 0,
      internMaxPage: false,
    })
    //请求数据，设置数据（页面标志，当前页面，页面数据大小，页面数据）
    if (city == "所有城市") {
      this.setData({
        internFlag: "all",
        internKeyword: "",
      })
      //实习职位数据列表
      companyUtil.listInternshipPosition("", _this.data.internFlag, 0, this.data.pageSize).then((res) => {
        _this.setData({
          internshipPositionData: res
        })
      })
    } else {
      var internPageNow = _this.data.internPageNow;
      var pageSize = _this.data.pageSize;
      companyUtil.listInternshipPosition(city, "byCity", internPageNow, pageSize).then((res) => {
        _this.setData({
          internshipPositionData: res,
          internship_loading: false,
          internship_haveMore: false,
        })
      })
    }
  },

  //实习职位上拉加载
  internshipOnReachBottom: function(e) {
    var _this = this;
    if (!_this.data.maxPage) {
      this.setData({
        pageNow: (this.data.pageNow + 1),
        loading: true,
        haveMore: true
      })
      //获取标志，请求参数和页面数据
      var keyWord = this.data.keyWord;
      var flag = this.data.dataFlag;
      var pageNow = this.data.pageNow;
      var pageSize = this.data.pageSize;
      companyUtil.getCompanies(keyWord, flag, pageNow, pageSize).then((res) => {
        if (res == "" || res == null || res.length == 0) {
          _this.setData({
            maxPage: true,
            loading: false,
            haveMore: false
          })
        } else {
          var gotCompanies = res;
          //增加收藏状态
          var companyIdsOfCollection = _this.data.companyIdsOfCollection;
          gotCompanies = companyUtil.addCollectedStatus(gotCompanies, companyIdsOfCollection);
          _this.setData({
            companies: _this.data.companies.concat(gotCompanies),
            loading: false,
            dataFlag: flag,
            maxPage: false,
          })
        }
      })
    } else {
      this.setData({
        loading: false,
        haveMore: false
      })
    }
  },

  //进入实习职位详情页面
  goInternshipDetail: function(e) {
    wx.navigateTo({
      url: '/pages/company/internship_detail/internship_detail?id=' + e.currentTarget.dataset.id,
    })
  },


})